package com.xhs.minio.core.interceptor;

import cn.hutool.core.util.IdUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @desc: 日志拦截器，对日志增加唯一标识
 * @projectName: spring-boot-minio
 * @author: xhs
 * @date: 2025-08-16 周六 16:57
 */
@Component
public class LoggingInterceptor implements HandlerInterceptor {

    /**
     * 日志唯一标识
     */
    private static final String LOG_ID = "logId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String simpleUUID = IdUtil.simpleUUID();
        String logId =String.format("[logId:%s]", simpleUUID);
        request.setAttribute(LOG_ID, logId);
        MDC.put(LOG_ID, logId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        try {
            String logId = (String) request.getAttribute(LOG_ID);
            if (logId != null) {
                MDC.put(LOG_ID, logId);
            }
        } finally {
            MDC.remove(LOG_ID);
        }
    }
}
